#!/usr/bin/env python
# coding=utf-8
# Author:  vavava

from vavava.util import LogAdapter
from vavava.util import assure_path
from vavava.httpclient import HttpClient
from vavava.util import reg_helper
from PIL import Image
import re

TESSDATA_PATH=r'./spiders/tessdata'

class FetchTrack2:
    def __init__(self,item="UQU1008685",log=None):
        self.log=LogAdapter(log)
        self.item_id = item
        self.random_id = ""
        self.wc = HttpClient()
        self.charset = 'ISO-8859-1'
        self.wc.req_timeout = 20
        self.tessercat_result = ""

    def get_data(self):
        url1 = r'http://auspost.com.au/track/track.html?id=%s' % self.item_id
        url_root = r'http://auspost.com.au/track/'
        resp1 = self.wc.Get(url1)
        if not resp1:
            return

        html1 = resp1.decode(self.charset)
        reg_str = r'captcha\.html\?ts=(?P<random_id>[^"]*)'
        results = reg_helper(html1,reg_str)
        if not results:
            self.log.debug("failed to get random id:item_id=%s" % self.item_id )
            return

        self.random_id = results[0]
        url2 = r'http://auspost.com.au/track/captcha.html?ts=%s' % self.random_id
        self.wc.header_refer_ = url1
        resp2 = self.wc.Get(url2)
        if not resp2:
            self.log.debug("failed to get security code:item_id=%s" % self.item_id )
            return

        #tessercat
        from vavava.tesseract import Tesseract4py
        path  = TESSDATA_PATH
        lang  = r'auspost'
        tess = Tesseract4py(path,lang)
        import codecs
        tmpfile = r"./tmp/%s.jpg" % self.random_id
        assure_path(r'./tmp/')
        f = codecs.open(tmpfile,"wb")
        f.write(resp2)
        f.close()
        self.tessercat_result = tess.img_to_string(tmpfile)

        self.log.debug("random_id=%s-->img=%s--->result=%s" %
                       (self.random_id,tmpfile,self.tessercat_result) )

        url3 = r'http://auspost.com.au/track/track.html'
        postdata = {
            "trackIds":self.item_id,
            "captchaChallenge":self.tessercat_result
        }
        resp3 = self.wc.Post(url3,postdata)
        html3 = resp3.decode(self.charset)
        #self.log.debug(html3)

        reg_str=r'<a\s*name="emailNotification">[^<]*</a>[^<]*<table[^>]*>.*</table>'
        reg = re.compile(reg_str,re.S)
        match = reg.findall(html3)
        if not match :
            self.log.info("failed：%s" % self.item_id)
        else:
            self.log.info("success：%s" % self.item_id)
            return self.get_trs(match[0])

if __name__ == "__main__":
    track = FetchTrack2()
    track.get_data()
